﻿//=============================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 作 者：江怀玉
// 日 期：2011-10-11
// 描 述: 用于生成数据结果的JSON数据格式
// URL parameter:
//        entity:当前实体对象名称(不一定是表名)
//        codition:过滤数据条件
//        pageindex:当前页
//        pagesize:页记录数
//        type:JSON的数据类型，有时候用于List.aspx使用，有时用于生成对应的JS Object Entity!
//        order:排序
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉    
// 1.01   2011/11/21   江怀玉            增加获取数据权限功能
// 1.02   2011/11/23   江怀玉            增加获取自定义查询条件功能
//
//=============================================================
using System;
using System.Collections.Generic;
using System.Web;
using ZX.Common;
using ZX.DBModule;
using System.Text;


using ZX.BLL.Extend;

namespace ZX.Web.UI.Controls
{
    public partial class DataTableJSONList : BasePage
    {
        public string NoDbClick;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (GetStringFromQueryString("action", "") == "getInstance")
            { 
                getInstance();
            }
            else
            {
                getData();
            }
            //iSunContext.Current.Context.Response.Write("["+str+"]");
        }


        /// <summary>aj
        /// 获取实体
        /// </summary>
        private void getInstance()
        {
            string strEntity = this.GetStringFromQueryString("entity", "DatUser");
            DataTableBaseEntity entity = new DataTableBaseEntity();
            entity.TableName = strEntity;
            entity.CreateDT();
            entity.DRow[entity.getKey()] = Guid.NewGuid();
            entity.EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
            HttpContext.Current.Response.Write(entity.EntityJson.Replace("\\\\\"", "\\\"").Replace("\\", "\\\\"));
        }
        
        private void getData()
        {
            //if (this.UserId == null)
            //{
            //    Response.Write("[]");
            //    return;
            //}
            string strEntity = this.GetStringFromQueryString("entity", "DatUser");            //对应的实体
            string strCondition = this.GetStringFromQueryString("condition", "");            //系统特定条件
            string strCustomCondition = this.GetStringFromQueryString("customCondition", "");//自定义条件
            int iPageIndex = this.GetIntFromQueryString("pageindex", 0);                     //第N页？
            int iPageSize = this.GetIntFromQueryString("pagesize", 0);                       //页记录数？
            string IsOnlyTotal = this.GetStringFromQueryString("onlyTotal", "false");         //是否只回传记录总数?
            string IsDesc = this.GetStringFromQueryString("desc", "Yes");                  //Yes or No
            string strGetTotalFields = this.GetStringFromQueryString("getTotalFields", "");                // 指定需要SUM的字段  
            string getSumFlag = this.GetStringFromQueryString("getSumFlag", "");

            // strCondition = Server.UrlDecode(strCondition);
            // strCustomCondition = Server.UrlDecode(strCustomCondition);
            // 系统数据权限
            strCondition = strCondition == "" ? getRoleCondition() : strCondition + (getRoleCondition() == "" ? "" : " and " + getRoleCondition());
            strCondition = strCondition == "" ? strCustomCondition : strCondition + (strCustomCondition == "" ? "" : " and " + strCustomCondition);


            strCustomCondition = strCustomCondition
                     .Replace("@UserID", this.UserId.ToString())
                     .Replace("@UserName", this.UserName);
            strCondition = strCondition
                                 .Replace("@UserID", this.UserId.ToString())
                                 .Replace("@UserName", this.UserName);


            string strType = this.GetStringFromQueryString("type", "");
            string strOrder = this.GetStringFromQueryString("order", "");
            strEntity = strEntity.Split(',')[0];

            BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;

            if (entity == null)
            {
                entity = new DataTableBaseEntity();
                var _entity = entity as DataTableBaseEntity;
                //_entity.TableKey = _entity.GetTableId();
                _entity.TableName = strEntity;
            }
            else
            {
                strEntity = entity.GetTableName();
                entity = new DataTableBaseEntity();
                (entity as DataTableBaseEntity).TableName = strEntity;
            }

            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
           iPageSize= iPageSize == 0 ? 25 : iPageSize;
            bll.PageIndex = iPageIndex;
            bll.PageSize = iPageSize;
            bll.Order = strOrder;
            bll.Desc = IsDesc;//"Yes";//2012.6.18改
            System.Data.DataTable list;
            int totalrecord =0;

//            剩余调休
//            if (strEntity.ToLower() == "v_wkremtovertimeleave" && !strCondition.Contains("AddUser"))
//            {
//                string sqlorder = " order by LDeptName,CName ";
//                string srhSql = @"select EmployeeID,EmployeeCode,CName,LDeptName,
//                        SUM(WorkDayOverTime) WorkDayOverTime,SUM(WeekendOverTime) WeekendOverTime,SUM(HolidayOverTime) HolidayOverTime,SUM(TotalOverTime) TotalOverTime,
//                        SUM(TiaoxiuTime) TiaoxiuTime,SUM(RemTime) RemTime,dbo.Fn_GetEmployeeRemOvertimeLeave(EmployeeID) RemTiaoxiuTime
//                        from V_wkOvertimeLeave
//                        where 1=1 {0}
//                        group by EmployeeID,EmployeeCode,CName,LDeptName
//                        {1}";
//                //分页SQL
//                string pagesql = @"SELECT TOP {0} * FROM  (  
//	                        SELECT ROW_NUMBER() OVER( {1} )  AS RowNumber,* FROM ({2})V where 1=1
//	                        ) A 
//                        WHERE RowNumber > {3} ";
//                list = bll.GetDataTableBySqlComm(string.Format(srhSql, strCondition, sqlorder));

//                //总记录数
//                totalrecord = list.Rows.Count;
//                if (IsOnlyTotal == "true")
//                {
//                    Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
//                    return;
//                }
//                //分页
//                if (bll.PageIndex > 0)
//                {
//                    list = bll.GetDataTableBySqlComm(string.Format(pagesql, iPageSize, sqlorder, string.Format(srhSql, strCondition, ""), (iPageIndex - 1) * iPageSize));
//                }
//                if (list == null)
//                {
//                    HttpContext.Current.Response.Write("[{\"N\":\"null\"}]");
//                    return;
//                }
//            }
            //if (strEntity.ToLower() == "crmorderpaydelivercollect") //交付明细汇总
            //{
            //    //分页SQL
            //    ZX.CRM.Bussiness.BCrmOrderPayDeliverCollect services = new ZX.CRM.Bussiness.BCrmOrderPayDeliverCollect();
            //    ZX.CRM.Library.CrmOrderPayDeliverCollect info = new ZX.CRM.Library.CrmOrderPayDeliverCollect();
            //    string data = this.GetStringFromQueryString("customCondition", ""); 

            //    DateTime dt = System.DateTime.Now;
            //    info.BeginDate = dt.AddDays(1 - dt.Day);
            //    info.EndDate = info.BeginDate.AddMonths(1).AddDays(-1);
            //    int flag = 0;

            //    if (!string.IsNullOrEmpty(data))
            //    {
            //        var objEntity = new { BeginDate = string.Empty, EndDate = string.Empty, DeptId = string.Empty, CustomerName = string.Empty, PackName = string.Empty, Product = string.Empty, SaleTypeName = string.Empty, SelType = 0 };
            //        var obj = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(data, objEntity);
            //        if (obj != null)
            //        {
            //            if (!string.IsNullOrEmpty(obj.BeginDate)) info.BeginDate = Convert.ToDateTime(obj.BeginDate);
            //            if (!string.IsNullOrEmpty(obj.EndDate)) info.EndDate = Convert.ToDateTime(obj.EndDate);
            //            info.DeptId = new Guid(string.IsNullOrEmpty(obj.DeptId) ? "00000000-0000-0000-0000-000000000000" : obj.DeptId);
            //            info.CustomerName = obj.CustomerName;
            //            info.PackName = obj.PackName;
            //            info.Product = obj.Product;
            //            info.SaleTypeName = obj.SaleTypeName;
            //            flag = obj.SelType;
            //        }
            //    }
            //    //else  //不能默认用户当前组织架构，否则需要判断当前用户数据权限范围
            //    //{
            //    //    ZX.BLL.Extend.BaseBussnies deptUserPost = new ZX.BLL.Extend.BaseBussnies();
            //    //    deptUserPost.entity = new ZX.CRM.Library.V_UserEmp();
            //    //    System.Collections.Generic.IList<ZX.CRM.Library.V_UserEmp> lscurUserTemp = deptUserPost.GetEntitys<ZX.CRM.Library.V_UserEmp>(string.Format("userid='{0}' and IsExpire=0", this.UserId));
            //    //    if (lscurUserTemp != null && lscurUserTemp.Count > 0)
            //    //    {
            //    //        ZX.CRM.Library.V_UserEmp userinfo = lscurUserTemp[0];
            //    //        info.DeptId = userinfo.DeptID;
            //    //        flag = 1;
            //    //    }
            //    //}

            //    //条件下的总记录数
            //    if (IsOnlyTotal == "true")
            //    {
            //        totalrecord = (info.DeptId == Guid.Empty) ? 0 : services.CrmOrderPayDeliverCollectCount(info, flag);
            //        Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
            //        return;
            //    }

            //    list = (info.DeptId == Guid.Empty) ? null : services.Seach(info, flag, iPageSize, iPageIndex, out totalrecord);

            //    if (list == null)
            //    {
            //        HttpContext.Current.Response.Write("[{\"N\":\"null\"}]");
            //        return;
            //    }
            //}
            //else
            //{
                // 指定SUM的字段 Added on 06m/04/2015 by zengfei

                //if (strGetTotalFields != "")
                //{
                //    char[] separator = {','};
                //    string[] fields;
                //    fields = strGetTotalFields.Split(separator);
                //    string strField = "";

                //    foreach (var field in fields)
                //    {
                //        if (strField == "")
                //        {
                //            strField = "sum(" + field + ") as " + field;
                //        }
                //        else
                //        {
                //            strField = ",sum(" + field + ") as " + field;
                //        }
                //    }

                //    System.Data.DataTable dt = new System.Data.DataTable();
                //    ZX.DAL.DBExtend.DbSql db = new ZX.DAL.DBExtend.DbSql();
                //    string sumResult; 

                //    sumResult = ZX.Common.Globals.Dtb2Json(db.ExecuteQuery("select " + strField + " from " + strEntity + " where 1=1 " + strCondition));
                //    Response.Write(sumResult);
                //    return;
                //}
                //
                if (getSumFlag == "true")
                { 
                    WebExtend.SumFields sf = new WebExtend.SumFields(strEntity);
                    System.Data.DataTable dtResult = sf.GetSumResult(strCondition);
                    String result = "";

                    if (dtResult.Rows.Count > 0)    // Sum 只返回一条记录
                    {
                        for (int i = 0; i < dtResult.Columns.Count; i++)
                        {
                            result = result + (result == "" ? "" : "&nbsp;&nbsp;&nbsp;&nbsp;") + dtResult.Columns[i].ColumnName + ": " + dtResult.Rows[0][i].ToString();
                        }
                    }
                    Response.Write(result);
                    //Response.Write(ZX.Common.Globals.Dtb2Json(sf.GetSumResult(strCondition)));
                    return;
                }
                
                totalrecord = bll.GetRowCount(strCondition);
                if (IsOnlyTotal == "true")
                {
                    Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
                    return;
                }
                if (bll.PageIndex > 0)
                {
                    list = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableSplitPage("1=1") : bll.GetDataTableSplitPage(strCondition);
                }
                else
                {
                    list = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableByCondition("1=1") : bll.GetDataTableByCondition(strCondition);
                }
                if (list == null)
                {
                    HttpContext.Current.Response.Write("[{\"N\":\"null\"}]");
                    return;
                }
            //}

            ////
            /// 解密
            ////
            if (strEntity.Contains("salEmployeeSalaryResult") || strEntity == "V_salBaseSalary" || strEntity.Contains("salSalaryInterception") || strEntity.Contains("salSalaryReissue") || strEntity == "V_salOvertimeFee" ||
                strEntity == "V_salBasicSubsidy" || strEntity == "V_salLargeClassBonus" || strEntity == "V_salPerformanceBonus")
            {
                EncryptData.EncryptSalary.DecryptLists(strEntity, list);
            }


            //int totalrecord = bll.GetRowCount(strCondition);
            string strFormat = "{\"total\":" + totalrecord.ToString() + ",\"rows\":";
            string str = ZX.Common.Globals.DataTableToJSON(list).Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("@@", " ");
            strFormat = strFormat + str + "}";
            //strFormat = strFormat.Replace(new Regex("(^|[^\\\\])\\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\\"","$1new Date($2)");
            switch (strType)
            {
                case "1":
                    HttpContext.Current.Response.Write("[" + str.Replace("null", "").Replace("[A]", "&") + "]");
                    break;
                case "2":
                    HttpContext.Current.Response.Write("var _Data" + strEntity + " = " + strFormat + ";");
                    break;
                default:
                    HttpContext.Current.Response.Write(strFormat);
                    break;

            }
        }

        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(this.UserId, this.FunctionID);
            StringBuilder strCondition = new StringBuilder("");

            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        if (this.EntityName == "V_HF_TaskInstanceView")
                        {
                            strCondition.Append(string.Format(" opercontent='ALL' or opercontent='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (this.EntityName == "V_HF_ClaimedWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (this.EntityName == "V_HF_CompleteWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (this.EntityName == "V_HF_MyAllWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (this.EntityName == "V_HF_AbnormalTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        /* else if (this.EntityName == "V_CrmCustomerInfo")
                         {
                             string strTreeId = this.GetStringFromQueryString("condition", "");
                             if (strTreeId == "")
                             {
                                 strCondition.Append(string.Format(" CustomUser='{0}'", this.UserId));
                             }
                             else
                             {
                                 strCondition.Append(string.Format(" {0}", strTreeId));
                             }
                         }
                         else if (this.EntityName == "V_CrmCustomer")
                         {
                             strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate=0", this.UserId));
                         }*/
                        else if (this.EntityName == "CrmPreCustomerData")
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(string.Format(" UserId='{0}'", this.UserId));
                        }
                        else
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(string.Format(" AddUser='{0}'", this.UserId));
                        }
                        break;
                    ///可以看本部门的
                    case "1":
                        if ((this.EntityName == "V_CrmCustomerShow" || this.EntityName == "V_CrmCustomerList"))
                        {
                            //strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate=0 and IsValue=1", this.UserId));
                            strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and IsValue='1'", this.UserId));
                        }else if (this.EntityName == "V_CrmCustomerInfo")
                        {
                            string strTreeId = this.GetStringFromQueryString("condition", "");
                            if (strTreeId == "")
                            {
                                strCondition.Append(string.Format(" CustomUser='{0}' and IsValue='1'", this.UserId));
                            }
                            /*else
                            {
                                strCondition.Append(string.Format(" {0}", strTreeId));
                            }*/
                        }
                        else
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(string.Format(" AddUser in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        break;
                    // 全部数据
                    case "2":
                        break;
                    //自定义部门条件
                    case "3":
                        // 如果自定义条件
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append(string.Format(" AddUser in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        break;
                    // 自定义条件数据
                    case "4":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        if (entity.Condition != string.Empty)
                        {
                            strCondition.Append(" " + entity.Condition + " ");
                        }
                        break;
                    default:
                        break;
                }
            }

            //只用客户用户时使用
            if (this.User.IsOutsite == true)
            {
                if (this.EntityName == "TrActivity")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID='{0}')", User.CustomerID));

                }
                if (this.EntityName == "V_TrActivityCourse")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID = '{0}')", User.CustomerID));
               }

               
            }
            if (this.EntityName == "V_TrStudyGain")
            {
                if (strCondition.ToString() != "")
                {
                    strCondition.Append(" OR ");
                }

                strCondition.Append(string.Format("(PrincipalHrmanno = '{0}')", this.UserId));
            }

            return string.IsNullOrEmpty(strCondition.ToString())?"": "("+ strCondition.ToString()+")";
            //this.UserId
        }

    }
}
